import logging

from django import http
from django.shortcuts import render
from django.views import View
from django.core.cache import cache
from areas.models import Area
from utils.response_code import RETCODE

logger = logging.getLogger("django")


# Create your views here.
class AreasView(View):
    """省市区联动"""

    # 缓存默认在default的配置中
    def get(self, request):
        area_id = request.GET.get("area_id")
        if not area_id:
            """查询省"""
            province_list = cache.get('province_list')

            if not province_list:
                # 没有缓存
                # 属性值__条件表达式=值
                try:
                    province_model_list = Area.objects.filter(parent__isnull=True)
                    # 将query——set转 字典列表
                    province_list = []
                    for model_obj in province_model_list:
                        province_dict = {
                            "id": model_obj.id,
                            "name": model_obj.name
                        }
                        province_list.append(province_dict)
                    # 存储省份缓存数据
                    cache.set('province_list', province_list, 3600)
                    # 优化后可以简写
                    # return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "province_list": province_list})
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "数据查询异常"})
            # 有缓存
            return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "province_list": province_list})
        else:
            """查询市区"""
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:

                    # parent_model = Area.objects.get(id=area_id)  # 方法2
                    ## city_model_list = parent_model.area_set.all()
                    # city_model_list = parent_model.subs.all()

                    city_model_list = Area.objects.filter(parent__id=area_id)  # 方法一
                    # 将query——set转 字典列表
                    list_cache = []
                    for model_obj in city_model_list:
                        city_dict = {
                            "id": model_obj.id,
                            "name": model_obj.name
                        }
                        list_cache.append(city_dict)

                    sub_data = {
                        "id": area_id,
                        "name": Area.objects.get(id=area_id).name,
                        "subs": list_cache
                    }
                    # 添加缓存
                    # 储存市或区缓存数据
                    cache.set('sub_area_' + area_id, sub_data, 3600)

                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "数据查询异常"})

            return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK", "sub_data": sub_data})
